package com.tencent.yolov8ncnn;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

// 在类顶部添加导入
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.FileOutputStream;


public class AssetImageLoader {
    private static final String IMAGE_DIR = "val/images";
    private static final Set<String> IMAGE_EXTENSIONS = new HashSet<>(Arrays.asList("png", "jpg", "jpeg"));

//    public static void loadImages(Context context,Yolov8Ncnn yolov8Ncnn) {
//
//        AssetManager assetManager = context.getAssets();
//
//        try {
//            // 列出目录下的所有文件和子目录
//            String[] files = assetManager.list(IMAGE_DIR);
//            if (files == null || files.length == 0) {
//                Log.e("AssetImageLoader", "目录不存在或为空: " + IMAGE_DIR);
//
//            }
//
//            // 过滤出图片文件
//            for (String file : files) {
//                if (isImageFile(file)) {
//                    String filePath = IMAGE_DIR + "/" + file; // 注意路径拼接
//                    try (InputStream is = assetManager.open(filePath)) {
//                        Bitmap bitmap = BitmapFactory.decodeStream(is);
//                        if (bitmap != null) {
//                            yolov8Ncnn.processImage(bitmap);
//                        } else {
//                            Log.w("AssetImageLoader", "无法解码文件: " + filePath);
//                        }
//                    } catch (IOException e) {
//                        Log.e("AssetImageLoader", "加载图片失败: " + filePath, e);
//                    }
//                }
//            }
//        } catch (IOException e) {
//            Log.e("AssetImageLoader", "访问目录失败: " + IMAGE_DIR, e);
//        }
//
//    }
//
    // 检查文件是否为图片（根据扩展名）
    private static boolean isImageFile(String fileName) {
        String extension = getFileExtension(fileName);
        return extension != null && IMAGE_EXTENSIONS.contains(extension);
    }

    // 获取文件扩展名（小写）
    private static String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex >= 0 && lastDotIndex < fileName.length() - 1) {
            return fileName.substring(lastDotIndex + 1).toLowerCase();
        }
        return null;
    }



    public static void loadImages(Context context, Yolov8Ncnn yolov8Ncnn,  File outputFolder) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Handler handler = new Handler(Looper.getMainLooper());
        executor.execute(() -> {
            AssetManager assetManager = context.getAssets();

            try {
                String[] files = assetManager.list(IMAGE_DIR);
                if (files != null) {
                    int total = files.length;
                    for (int i = 0; i < total; i++) {
                        String file = files[i];
                        if (isImageFile(file)) {
                            String filePath = IMAGE_DIR + "/" + file;
                            try (InputStream is = assetManager.open(filePath)) {
                                Bitmap bitmap = BitmapFactory.decodeStream(is);
                                if (bitmap != null) {

                                    Log.d("AssetImageLoader", "准备处理图片！");
                                    // 传递图片名称给Native层
                                    String imageName = file.substring(0, file.lastIndexOf('.'));
                                    yolov8Ncnn.processImage(bitmap, imageName, assetManager);
                                    // Bitmap result = yolov8Ncnn.getProcessedImage();

                                    Log.d("AssetImageLoader", "获取检测结果！");
//                                    yolov8Ncnn.getDetectionResults();
//                                    Log.d("AssetImageLoader", "检测结果已经获取完毕！");
                                    // 保存结果
                                    // saveDetectionResult(context, outputFolder, file, result, yolov8Ncnn.getDetectionResults());

                                    // 更新UI（主线程）
                                    int finalI = i;
                                    handler.post(() -> Toast.makeText(context,
                                            ": " + (finalI + 1) + "/" + total,
                                            Toast.LENGTH_SHORT).show());
                                }
                            }
                        }
                    }
                }
            } catch (IOException e) {
                Log.e("AssetImageLoader", "加载图片失败", e);
                handler.post(() -> Toast.makeText(context, "加载失败", Toast.LENGTH_SHORT).show());
            }
        });
    }



    private static void saveDetectionResult(Context context, File outputFolder, String originalFileName, Bitmap resultImage, List<DetectionResult> results) {
        try {
            // 获取原文件名（不含扩展名）
            String baseName = originalFileName.substring(0, originalFileName.lastIndexOf('.'));

            // 保存图片
            File imageFile = new File(outputFolder, "detected_" + baseName + ".jpg");
            try (FileOutputStream fos = new FileOutputStream(imageFile)) {
                resultImage.compress(Bitmap.CompressFormat.JPEG, 95, fos);
            }

            // 保存检测结果文本
            File resultFile = new File(outputFolder, "result_" + baseName + ".txt");
            try (FileOutputStream fos = new FileOutputStream(resultFile)) {
                StringBuilder sb = new StringBuilder();
                sb.append("检测结果 - ").append(originalFileName).append("\n\n");
                sb.append("检测到 ").append(results.size()).append(" 个对象:\n");

                for (DetectionResult res : results) {
                    sb.append(String.format("- 类别: %s, 置信度: %.2f%%, 位置: [x=%.1f, y=%.1f, w=%.1f, h=%.1f]\n",
                            res.label, res.confidence * 100,
                            res.rectX, res.rectY, res.rectWidth, res.rectHeight)); // 使用直接字段访问
                }

                fos.write(sb.toString().getBytes());
            }

            Log.d("AssetImageLoader", "保存结果: " + imageFile.getName() + " 和 " + resultFile.getName());
        } catch (IOException e) {
            Log.e("AssetImageLoader", "保存结果失败", e);
        }
    }






}




